package main

import (
	"archive/zip"
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"github.com/milvus-io/milvus-sdk-go/v2/client"
	"github.com/milvus-io/milvus-sdk-go/v2/entity"
	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"github.com/streadway/amqp"
	"image"
	_ "image/png" // 导入png格式支持
	"io"
	"io/ioutil"
	"log"
	"mime/multipart"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"strings"
)

func main() {
	//walkFiles()
	//url := "http://192.168.30.251:8088/testbucket/kellie2445_Illustration_of_massive_website_traffic_generation.__7b7c2147-5065-4a88-b596-1ad1edd1cb04.png"
	//sendGrpcMsg()
	//receiveMessage()
	createMilvusCollect()
	//milvusQuery()
	// 读取 JSON 文件

	//var str = "Picture of a men age around 40 years who started having problems with presbyopia by realistic  . He tried to look at the mobile phone or book clearly but he can’t do it ."
	//parts := strings.SplitN(str, "--", 2)
	//fmt.Println(parts)

}

// milvus 查询数据
func milvusQuery() {
	milvusClient, err := client.NewGrpcClient(
		context.Background(), // ctx
		"10.10.22.104:19530", // addr
	)
	if err != nil {
		log.Fatal("failed to connect to Milvus:", err.Error())
	}

	defer milvusClient.Close()

	var (
		collectionName = "gallery5"
	)
	opt := client.SearchQueryOptionFunc(func(option *client.SearchQueryOption) {
		option.Limit = 10
		option.Offset = 0
		option.ConsistencyLevel = entity.ClStrong
		option.IgnoreGrowing = false
	})

	sp, _ := entity.NewIndexIvfFlatSearchParam( // NewIndex*SearchParam func
		10, // searchParam
	)
	vectors :=
		[]float32{
			0.2059963494539261,
			-0.22202134132385254,
			0.023623108863830566,
			-0.013108696788549423,
			0.39337074756622314,
			0.5423734188079834,
			0.01704198122024536,
			-0.04314113408327103,
			0.3627755045890808,
			-0.06529650092124939,
			-0.20547479391098022,
			-0.3094039857387543,
			0.3965685963630676,
			-0.06669753789901733,
			-0.16277125477790833,
			-0.11241307109594345,
			0.16444215178489685,
			-0.04229270666837692,
			-0.2686171531677246,
			-0.022240616381168365,
			-0.033218033611774445,
			0.05003517121076584,
			-0.6631380319595337,
			0.16367310285568237,
			-0.11881018429994583,
			-0.4389725923538208,
			-0.39833927154541016,
			0.14110590517520905,
			-0.04170726239681244,
			-0.048723042011260986,
			0.14563748240470886,
			0.03588683903217316,
			0.39673662185668945,
			-0.21222874522209167,
			-0.043303728103637695,
			-0.05944381654262543,
			0.27304700016975403,
			-0.08290091156959534,
			0.09900292754173279,
			-0.27886849641799927,
			-0.17578113079071045,
			-0.5429603457450867,
			0.11449259519577026,
			-0.2854011654853821,
			0.045353442430496216,
			-0.2871575951576233,
			-0.07956913113594055,
			-0.003921568393707275,
			-0.04285269230604172,
			-0.15820012986660004,
			-0.044582027941942215,
			-0.18769650161266327,
			-0.2151392251253128,
			0.04700189083814621,
			-0.16548368334770203,
			-0.02485942840576172,
			-0.1744309514760971,
			0.3135257363319397,
			0.20778635144233704,
			-0.09519719332456589,
			0.15782949328422546,
			0.1236596405506134,
			-0.1450105905532837,
			0.2805459499359131,
			0.051847025752067566,
			0.22777165472507477,
			-0.06606459617614746,
			0.08601841330528259,
			0.30222955346107483,
			-0.11808657646179199,
			-0.1380859613418579,
			0.43130117654800415,
			-0.17143574357032776,
			0.14740167558193207,
			0.07740341126918793,
			-0.1268293857574463,
			-0.16318386793136597,
			-0.021278783679008484,
			0.11158852279186249,
			-0.292263001203537,
			0.47197797894477844,
			0.3418002724647522,
			-0.5134627819061279,
			-0.11431220173835754,
			-0.2684628963470459,
			0.12673033773899078,
			-0.1706164926290512,
			0.5042847394943237,
			0.05534099042415619,
			0.4664428234100342,
			-0.11307953298091888,
			0.275138795375824,
			-0.2101738601922989,
			-0.015174999833106995,
			-0.21903663873672485,
			-0.25160354375839233,
			-1.2496397495269775,
			-0.06422732770442963,
			0.2800971567630768,
			-0.21180613338947296,
			-0.1016702950000763,
			-0.24939000606536865,
			0.1433085948228836,
			-0.05350623279809952,
			-0.15516352653503418,
			-0.0750003382563591,
			-0.051040247082710266,
			-0.26188889145851135,
			-0.28104907274246216,
			-0.2442408800125122,
			0.7280641198158264,
			0.1325620412826538,
			0.06816768646240234,
			0.14557377994060516,
			0.27812057733535767,
			0.06471089273691177,
			0.021575704216957092,
			0.16671617329120636,
			-0.047106802463531494,
			0.22832581400871277,
			-0.4313536286354065,
			-0.2652796804904938,
			-0.0539061464369297,
			0.32063353061676025,
			0.5265864729881287,
			-0.6257540583610535,
			0.11430688947439194,
			0.1265392303466797,
			0.09234421700239182,
			-0.0851704329252243,
			0.1237712949514389,
			-0.16386553645133972,
			-0.04132331907749176,
			0.09705080837011337,
			0.06945435702800751,
			-0.21484686434268951,
			-0.08974461257457733,
			0.4720040559768677,
			-0.36732226610183716,
			-0.3322250247001648,
			0.004078492522239685,
			-0.023101046681404114,
			-0.18539409339427948,
			0.03629504144191742,
			0.01875387132167816,
			-0.1869691014289856,
			-0.10141563415527344,
			0.36111193895339966,
			0.031379491090774536,
			-0.17437005043029785,
			-0.03806328773498535,
			0.13794298470020294,
			-0.1277734339237213,
			0.1158108189702034,
			-0.004142604768276215,
			0.08850376307964325,
			0.2577986717224121,
			0.17521725594997406,
			-0.08611680567264557,
			-0.020988143980503082,
			-0.05763313174247742,
			0.2186843752861023,
			0.08710432052612305,
			0.10427655279636383,
			-0.04177004098892212,
			0.03015337511897087,
			0.15173505246639252,
			0.7959582805633545,
			-0.06985466182231903,
			0.1596013605594635,
			0.13884049654006958,
			-0.06710146367549896,
			-0.08834359794855118,
			0.023059934377670288,
			0.1387070119380951,
			0.30578500032424927,
			0.21585379540920258,
			0.13777464628219604,
			0.050342291593551636,
			0.22279322147369385,
			0.03822743892669678,
			-0.18441402912139893,
			-0.00974079966545105,
			0.1008627861738205,
			-0.19029663503170013,
			-0.3119349181652069,
			0.16088742017745972,
			0.38129448890686035,
			-0.3007798194885254,
			0.0759509950876236,
			0.0340973436832428,
			0.16412240266799927,
			0.3908080756664276,
			-0.2145102173089981,
			0.09692211449146271,
			0.36078187823295593,
			-0.09867895394563675,
			0.0033934861421585083,
			-0.24507427215576172,
			0.0535762757062912,
			0.06617151200771332,
			0.2543332576751709,
			0.15720176696777344,
			0.3920544981956482,
			-0.2516118288040161,
			-0.32348504662513733,
			-0.03277239203453064,
			0.20123764872550964,
			-0.06673353910446167,
			-0.18701061606407166,
			-0.2532076835632324,
			0.052514731884002686,
			0.10427045077085495,
			-0.6007426977157593,
			0.07034417986869812,
			0.04039541631937027,
			0.3081250786781311,
			-0.15517696738243103,
			-0.2786104083061218,
			-0.05223667621612549,
			0.4179767072200775,
			0.23139196634292603,
			-0.05404943227767944,
			0.039819687604904175,
			-0.2675285339355469,
			0.012445233762264252,
			0.06466899812221527,
			0.0109328031539917,
			0.13979429006576538,
			-0.2822733223438263,
			-0.21391314268112183,
			0.047079116106033325,
			0.33136945962905884,
			-0.11036863178014755,
			0.05835361033678055,
			-0.4087439179420471,
			0.18323731422424316,
			-0.10095715522766113,
			-0.015071168541908264,
			-0.1650504767894745,
			0.23183327913284302,
			-0.0025489479303359985,
			-0.012570343911647797,
			0.12405075877904892,
			-0.1399187445640564,
			0.09212201833724976,
			0.0368448868393898,
			0.03400373458862305,
			0.2530171275138855,
			0.562957763671875,
			0.18795794248580933,
			-0.061187341809272766,
			-0.04395844042301178,
			-0.35798320174217224,
			0.4294719994068146,
			-0.017536800354719162,
			-0.29358094930648804,
			0.08356332778930664,
			0.011669538915157318,
			-0.18800488114356995,
			0.12938103079795837,
			0.12022921442985535,
			-0.043967653065919876,
			-0.12254220247268677,
			0.19366198778152466,
			0.7127993702888489,
			0.06742846965789795,
			0.2299422323703766,
			0.04739026352763176,
			-0.04559534788131714,
			0.022204697132110596,
			0.07394129037857056,
			0.2370832860469818,
			-0.20692114531993866,
			0.1068148985505104,
			-0.6926536560058594,
			-0.44490307569503784,
			-0.5559198260307312,
			-0.11895407736301422,
			-0.036962106823921204,
			-0.3851799964904785,
			-0.10604195296764374,
			-0.03161802887916565,
			-0.2702674865722656,
			0.20953968167304993,
			-0.4326949715614319,
			0.29021671414375305,
			0.041271477937698364,
			-0.16074058413505554,
			0.014184065163135529,
			-0.5627363920211792,
			-0.003112003207206726,
			1.7095386981964111,
			-0.15373432636260986,
			-0.14955554902553558,
			0.2486448734998703,
			0.009294316172599792,
			-0.1060139462351799,
			-0.18908128142356873,
			-0.14525003731250763,
			-0.456996887922287,
			0.1573651283979416,
			0.11550213396549225,
			-0.06721381843090057,
			-0.028800107538700104,
			-0.5618629455566406,
			-0.21789748966693878,
			-0.5575350522994995,
			0.007326006889343262,
			-0.24092012643814087,
			-0.13138025999069214,
			-0.05974965542554855,
			-0.039898574352264404,
			-0.04535169526934624,
			-0.3641837239265442,
			-0.06825056672096252,
			-0.005535148084163666,
			-0.03969073295593262,
			0.36881908774375916,
			0.21379733085632324,
			-0.04994191229343414,
			-0.08925091475248337,
			-0.19049273431301117,
			-0.20248691737651825,
			-0.43350738286972046,
			-0.09732995927333832,
			-0.27279895544052124,
			-0.06790553033351898,
			0.48172008991241455,
			0.12947052717208862,
			-0.02335517108440399,
			-0.012158483266830444,
			-0.10198235511779785,
			0.6242709159851074,
			0.16484393179416656,
			0.4527781009674072,
			0.25531861186027527,
			-0.2913133203983307,
			-0.014190373942255974,
			0.22304946184158325,
			-0.4505084753036499,
			-0.2699536383152008,
			0.05053305625915527,
			-0.09601905941963196,
			-0.35433441400527954,
			0.11790645122528076,
			-0.38070186972618103,
			0.11196344345808029,
			-0.4323871433734894,
			0.009866133332252502,
			0.5207505822181702,
			-0.04598099738359451,
			-0.6687135696411133,
			0.07261146605014801,
			-0.29592055082321167,
			-0.02876061201095581,
			-0.2692492604255676,
			-0.3919019401073456,
			-0.2904238700866699,
			-0.041183505207300186,
			0.06320060789585114,
			0.22934243083000183,
			8.291913986206055,
			0.1623145341873169,
			0.40449026226997375,
			0.04586690664291382,
			-0.11384186148643494,
			-0.05377427488565445,
			0.512608528137207,
			-0.06841607391834259,
			-0.22223427891731262,
			0.005436643958091736,
			0.11602094769477844,
			-0.11049311608076096,
			-0.17137423157691956,
			0.4300052523612976,
			0.019122064113616943,
			-0.2909166216850281,
			-0.018166452646255493,
			0.0517977699637413,
			-0.1344021111726761,
			-0.42113393545150757,
			-0.19999948143959045,
			0.03471563756465912,
			0.19717144966125488,
			-0.06620775163173676,
			0.09884372353553772,
			-0.20347602665424347,
			0.11807308346033096,
			0.17170819640159607,
			0.04741828888654709,
			0.003738805651664734,
			0.06525103747844696,
			-0.22737516462802887,
			0.47420719265937805,
			-0.08537048101425171,
			-0.4185810387134552,
			0.24236348271369934,
			0.1539565622806549,
			0.009886890649795532,
			-0.27435189485549927,
			-0.34926629066467285,
			-0.27156883478164673,
			-0.1756919026374817,
			0.028034135699272156,
			-0.29849183559417725,
			-0.15840333700180054,
			0.17553198337554932,
			-0.3562364876270294,
			0.408664345741272,
			-0.21193283796310425,
			-0.080228790640831,
			0.3317275643348694,
			0.3860669732093811,
			-0.31468573212623596,
			-0.005032256245613098,
			-0.04057501256465912,
			-0.0730879008769989,
			0.1499631702899933,
			-0.08819479495286942,
			0.06284891813993454,
			0.013644643127918243,
			0.21566134691238403,
			-0.001099608838558197,
			0.2598840594291687,
			0.06504853069782257,
			0.06185680627822876,
			-0.07999667525291443,
			0.004641517996788025,
			0.10821348428726196,
			-0.4473665952682495,
			0.12550951540470123,
			-0.21212708950042725,
			-0.028228208422660828,
			0.19703081250190735,
			0.1606927067041397,
			0.32474368810653687,
			-0.42877018451690674,
			-0.27462807297706604,
			-0.22201627492904663,
			-0.002302376553416252,
			-0.18788902461528778,
			1.4142420291900635,
			0.4288296103477478,
			-0.2325325608253479,
			0.24485081434249878,
			0.18911077082157135,
			0.004095837473869324,
			-0.5129114389419556,
			0.21311095356941223,
			0.027667514979839325,
			0.25212371349334717,
			-0.4732906222343445,
			0.28158658742904663,
			0.1358489692211151,
			-0.5067591071128845,
			-0.24420054256916046,
			-0.19777555763721466,
			-0.2075508087873459,
			0.2542685270309448,
			-0.28163963556289673,
			-0.4212149679660797,
			-0.03038126975297928,
			-0.06421543657779694,
			-0.1521681547164917,
			0.2327336072921753,
			-0.14368164539337158,
			-0.11179552972316742,
			0.26231813430786133,
			-0.19323061406612396,
			-0.2589952349662781,
			-0.37679341435432434,
			-0.029330305755138397,
			-0.06894275546073914,
			0.34144818782806396,
			0.3432030975818634,
			-0.053262025117874146,
			-0.3060457110404968,
			-0.21078012883663177,
			-0.1045650839805603,
			-0.23361340165138245,
			0.3160756230354309,
			0.3413127362728119,
			-0.10054320842027664,
			0.29937395453453064,
			0.1943838894367218,
			0.08629739284515381,
			-0.08971962332725525,
			-0.04911278560757637,
			0.20772366225719452,
			-0.29142358899116516,
			-0.15640130639076233,
			-0.05783802270889282,
			-0.19621461629867554,
			-0.6090139746665955,
			-0.10872602462768555,
			0.17522570490837097,
			0.6012057662010193,
			-0.39450404047966003,
			-0.2561730146408081,
			-0.32768315076828003,
			0.23346063494682312,
			0.062132328748703,
			0.23086941242218018,
			-0.07687194645404816,
			0.006338059902191162,
			-0.05484894663095474,
			-0.8621509075164795,
			-0.1697930097579956,
			-0.10542567074298859,
			0.39130160212516785,
			0.3557581305503845,
		}
	searchResult, err := milvusClient.Search(
		context.Background(), // ctx
		collectionName,       // CollectionName
		nil,                  // partitionNames
		"image_type == 1",    // expr
		[]string{"gallery_image_id", "deleted_at"},   // outputFields
		[]entity.Vector{entity.FloatVector(vectors)}, // vectors
		"embedding", // vectorField
		entity.L2,   // metricType
		10,          // topK
		sp,          // sp
		opt,         // search options
	)
	if err != nil {
		log.Fatal("fail to query collection:", err.Error())
	}
	deletedAtList := searchResult[0].Fields.GetColumn("deleted_at")
	d0, _ := deletedAtList.GetAsInt64(0)
	d1, _ := deletedAtList.GetAsInt64(1)
	fmt.Println(searchResult)
	fmt.Println(deletedAtList)
	fmt.Println(d0)
	fmt.Println(d1)
}

// 创建milvus 集合
func createMilvusCollect() {
	milvusClient, err := client.NewGrpcClient(
		context.Background(), // ctx
		"10.10.22.104:19530", // addr
		//"192.168.30.80:31530", // addr
	)
	if err != nil {
		log.Fatal("failed to connect to Milvus:", err.Error())
	}

	defer milvusClient.Close()

	var (
		collectionName = "galleryNew"
	)
	schema := &entity.Schema{
		CollectionName: collectionName,
		Description:    "画廊集合",
		Fields: []*entity.Field{
			{
				Name:       "id",
				DataType:   entity.FieldTypeInt64,
				PrimaryKey: true,
				AutoID:     true,
			},
			{
				Name:     "embedding",
				DataType: entity.FieldTypeFloatVector,
				TypeParams: map[string]string{
					"dim": "512",
				},
				Description: "嵌入向量",
			},
			{
				Name:        "image_type",
				DataType:    entity.FieldTypeInt32,
				Description: "图片类型，0:四宫格 1:放大2；2倍，3： 4倍放大 4: 8倍放大  5： AI无损放大 6： 降噪",
			},
			{
				Name:        "gallery_image_id",
				DataType:    entity.FieldTypeInt64,
				Description: "画廊表的id",
			},
			{
				Name:     "path",
				DataType: entity.FieldTypeVarChar,
				TypeParams: map[string]string{
					"max_length": "65535",
				},
				Description: "图片地址(可用于拼接各种分辨率)",
			},
			{
				Name:     "ai_model",
				DataType: entity.FieldTypeVarChar,
				TypeParams: map[string]string{
					"max_length": "65535",
				},
				Description: "ai模型",
			},
			{
				Name:     "model_version",
				DataType: entity.FieldTypeVarChar,
				TypeParams: map[string]string{
					"max_length": "65535",
				},
				Description: "模型版本",
			},
			{
				Name:     "prompt",
				DataType: entity.FieldTypeVarChar,
				TypeParams: map[string]string{
					"max_length": "65535",
				},
				Description: "提示词",
			},
			{
				Name:        "width",
				DataType:    entity.FieldTypeInt64,
				Description: "宽",
			},
			{
				Name:        "height",
				DataType:    entity.FieldTypeInt64,
				Description: "高",
			},
			{
				Name:        "aspectRatio",
				DataType:    entity.FieldTypeFloat,
				Description: "宽高比",
			},
			{
				Name:        "created_at",
				DataType:    entity.FieldTypeInt64,
				Description: "创建时间",
			},
			{
				Name:        "deleted_at",
				DataType:    entity.FieldTypeInt64,
				Description: "删除时间",
			},
		},
		EnableDynamicField: true,
	}

	err = milvusClient.CreateCollection(
		context.Background(), // ctx
		schema,
		2, // shardNum
	)
	if err != nil {
		log.Fatal("failed to create collection:", err.Error())
	}
	// 定义索引参数
	indexParams, _ := entity.NewIndexIvfFlat(entity.COSINE, 2048)
	// 为 embedding 字段创建索引
	err = milvusClient.CreateIndex(
		context.Background(), // ctx
		collectionName,       // collectionName
		"embedding",          // fieldName
		indexParams,          // indexParams
		true,
	)
	if err != nil {
		log.Fatal("failed to create index:", err.Error())
	}

}

func receiveMessage() {
	// 连接 RabbitMQ 服务器
	//conn, err := amqp.Dial("amqp://admin:admin@10.10.22.172:5672/my_vhost")
	conn, err := amqp.Dial("amqp://xd:123456@192.168.30.80:32412/my_vhost")
	//conn, err := amqp.Dial("amqp://admin:123456@192.168.30.80:32412/my_vhost")
	failOnError(err, "Failed to connect to RabbitMQ")
	defer conn.Close()

	// 创建一个 channel
	ch, err := conn.Channel()
	failOnError(err, "Failed to open a channel")
	defer ch.Close()

	// 注册一个消费者
	msgs, err := ch.Consume(
		"hello2", // 队列名称
		"",       // 消费者标签
		true,     // 自动应答
		false,    // 是否排他性
		false,    // 是否阻塞
		false,    // 不使用额外的属性
		nil,      // 额外的参数
	)
	failOnError(err, "Failed to register a consumer")

	// 处理接收到的消息
	forever := make(chan bool)

	go func() {
		for d := range msgs {
			log.Printf("Received a message: %s", d.Body)
		}
	}()

	log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
	<-forever
}
func failOnError(err error, msg string) {
	if err != nil {
		log.Fatalf("%s: %s", msg, err)
	}
}

// 连接 RabbitMQ 服务器
//var conn, _ = amqp.Dial("amqp://admin:admin@10.10.22.172:5672/my_vhost")

var conn, _ = amqp.Dial("amqp://xd:123456@192.168.30.80:32412/my_vhost")
var ch, _ = conn.Channel()

//failOnError(err, "Failed to connect to RabbitMQ")

func sendMessage(body string) {

	//defer conn.Close()

	// 创建一个 channel
	//ch, err := conn.Channel()
	//failOnError(err, "Failed to open a channel")
	//defer ch.Close()

	// 声明一个队列
	//_, err := ch.QueueDeclare(
	//	"aigcbus.gallery", // 队列名称
	//	false,             // 持久性
	//	false,             // 是否自动删除
	//	false,             // 排他性
	//	false,             // 不阻塞
	//	nil,               // 额外的属性
	//)
	//failOnError(err, "Failed to declare a queue")

	// 发送一条消息到队列
	//	body := `
	//		{
	//   "image_type": 1,
	//   "member_id": 24,
	//   "prompt": "test prompt",
	//   "url": "http://192.168.30.251:8088/testbucket/369gator369_An_idyllic_barndimonium_house_nestled_in_a_vineyard_8187cb1f-1658-41f2-840e-2f161b6710a1.png",
	//   "original_url": "http://192.168.30.251:8088/testbucket/369gator369_An_idyllic_barndimonium_house_nestled_in_a_vineyard_8187cb1f-1658-41f2-840e-2f161b6710a1.png",
	//   "size": "166666",
	//   "content_type": "image/png",
	//   "width": 1000,
	//   "height": 1000,
	//   "file_name": "aa.png",
	//	 "ai_model": "Midjourney",
	//	"model_version":"6.0",
	//	"additional_type": 0
	//}
	//`
	err := ch.Publish(
		"aigcbus.gallery", // 交换器名称
		"gallery",         // 路由键
		false,             // 强制性
		false,             // 立即发布
		amqp.Publishing{
			ContentType: "text/plain",
			Body:        []byte(body),
		})
	failOnError(err, "Failed to publish a message")

	//fmt.Println(" [x] Sent ", body)
}

type GetGalleryInfoRequest struct {
	ImageType        int32  `protobuf:"varint,1,opt,name=image_type,json=imageType,proto3" json:"image_type,omitempty"`
	MemberId         int64  `protobuf:"varint,2,opt,name=member_id,json=memberId,proto3" json:"member_id,omitempty"`
	Prompt           string `protobuf:"bytes,3,opt,name=prompt,proto3" json:"prompt,omitempty"`
	Url              string `protobuf:"bytes,4,opt,name=url,proto3" json:"url,omitempty"`
	OriginalUrl      string `protobuf:"bytes,5,opt,name=original_url,json=originalUrl,proto3" json:"original_url,omitempty"`
	Size             string `protobuf:"bytes,6,opt,name=size,proto3" json:"size,omitempty"`
	ContentType      string `protobuf:"bytes,7,opt,name=content_type,json=contentType,proto3" json:"content_type,omitempty"`
	Width            int64  `protobuf:"varint,8,opt,name=width,proto3" json:"width,omitempty"`
	Height           int64  `protobuf:"varint,9,opt,name=height,proto3" json:"height,omitempty"`
	FileName         string `protobuf:"bytes,10,opt,name=file_name,json=fileName,proto3" json:"file_name,omitempty"`
	ModelType        string `protobuf:"bytes,11,opt,name=model_type,json=modelType,proto3" json:"model_type,omitempty"`
	Version          string `protobuf:"bytes,12,opt,name=version,proto3" json:"version,omitempty"`
	MidjourneyTaskId string `protobuf:"bytes,13,opt,name=midjourney_task_id,json=midjourneyTaskId,proto3" json:"midjourney_task_id,omitempty"` // mj绘画id
	AdditionalType   int32  `protobuf:"varint,14,opt,name=additional_type,json=additionalType,proto3" json:"additional_type,omitempty"`        // 0 没有附加图 1是垫图 2混图
	Seed             string `protobuf:"bytes,15,opt,name=seed,proto3" json:"seed,omitempty"`                                                   //种子值
}

// 线上
var token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJ4ZC1kZXNpZ24tc2VydmljZSIsImV4cCI6MTcyNzQ5MzgwOCwiaWF0IjoxNzI3MjM0NjA4LCJpc3MiOiJ4ZC1taWRqb3VybmV5LXNlcnZlciIsIklEIjoyLCJVc2VybmFtZSI6IuWwj-eBsOeBsCIsIlJvbGVJZHMiOm51bGwsIlBsYXRGb3JtIjoyLCJNZW1iZXJTdGF0dXMiOjF9.kXNg3INGz3hWUv6Zq8VVvh2lPutA7tYV2yU2itOZa5WhDcp4mXpICCvunYEFAtPzQE9B_okNmsze2QIZY9iWXzJPHqMMaNdFpRrtljinPxlVC6mBbSUVmgwzEoEsnN-jqyobpofUXWAAZAQ59bn598o8pXsLyJi3dqvLgrpl7Fo"
var fileToken = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJ4ZC1kZXNpZ24iLCJleHAiOjE3Mjc4Mzk0MDksImlhdCI6MTcyNzIzNDYwOSwiaXNzIjoieGQtbWlkam91cm5leS1zZXJ2ZXIiLCJUb2tlblBvbGljeSI6eyIxIjpbeyJQZXJtaXNzaW9uIjoxLCJGaWxlRGlyIjoiL2FkZGl0aW9uYWwvMi9vcml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Pbd8N5sIHX6A0ZGQpL0sjdC_EQFf50bKCCVvf_QW_D1_xfaMgYO-rRi3LAd9XgFF7fj8Q"

func walkFiles() {

	// 要遍历的文件夹路径
	//folderPath := "zip"
	//folderPath := "C:\\Users\\Administrator\\Desktop\\test-zip"
	folderPath := "D:\\midjourney-genernal1-4\\demo01"
	uploadNum := 1
	// 遍历文件夹
	err := filepath.Walk(folderPath, func(path string, info os.FileInfo, err error) error {
		// 忽略文件夹本身和非 ZIP 文件
		if info.IsDir() || !strings.HasSuffix(strings.ToLower(path), ".zip") {
			return nil
		}

		// 解压缩 ZIP 文件
		zipReader, err := zip.OpenReader(path)
		if err != nil {
			log.Printf("failed to open ZIP file %s: %v", path, err)
			return nil
		}
		defer zipReader.Close()

		// 遍历 ZIP 文件中的文件
		for _, file := range zipReader.File {
			// 处理 JSON 文件
			if strings.HasSuffix(strings.ToLower(file.Name), ".json") {
				jsonFile, err := file.Open()
				if err != nil {
					log.Printf("failed to open JSON file %s in ZIP %s: %v", file.Name, path, err)
					continue
				}
				defer jsonFile.Close()

				// 读取并解析 JSON 文件
				var jsonData map[string]string
				if err := json.NewDecoder(jsonFile).Decode(&jsonData); err != nil {
					log.Printf("failed to decode JSON file %s in ZIP %s: %v", file.Name, path, err)
					continue
				}

				// 获取 JSON 文件名（去掉后缀）
				jsonFileName := strings.TrimSuffix(file.Name, filepath.Ext(file.Name))
				// 如果 JSON 文件名以 ".meta" 结尾，则去掉 ".meta" 后缀
				jsonFileName = strings.TrimSuffix(jsonFileName, ".meta")
				// 获取 JSON 对应的 PNG 文件名
				pngFileName := fmt.Sprintf("%s.png", jsonFileName)
				// 找到对应的 PNG 文件
				for _, zipFile := range zipReader.File {
					if zipFile.Name == pngFileName {
						prompt := jsonData["prompts"]
						// 如果字符串中包含 "http"，直接返回原始字符串
						if strings.Contains(prompt, "http") {
							continue
						}

						//// 将所有的 "- -" 替换为 "--"
						//prompt = strings.ReplaceAll(prompt, "- -", " --")
						//
						//// 使用正则表达式去除数字后面的空格
						//re := regexp.MustCompile(`(\d+)\s+`)
						//prompt = re.ReplaceAllString(prompt, "$1")

						// 打开 PNG 文件
						pngFile, err := zipFile.Open()
						// 使用 strings.Split 函数将字符串按照逗号分割成多个部分

						fileName := zipFile.Name
						oldSize := zipFile.FileInfo().Size()
						// 将 int64 转换为字符串
						size := strconv.FormatInt(oldSize, 10)
						uploadResp := httpUploadFile(fileName, pngFile)
						if uploadResp == nil || len(uploadResp.Resource) == 0 {
							fmt.Println("上传失败")
							continue
						}
						// 获取第一个部分并去掉末尾的空格

						pngFile2, _ := zipFile.Open()
						imgConfig, _, err := image.DecodeConfig(pngFile2)
						if err != nil {
							log.Fatalf("无法解码PNG文件：%v", err)
						}
						//newUrl := uploadFile(fileName, oldSize, pngFile)
						//fmt.Println(newUrl)
						//originalUrl := fmt.Sprintf("http://10.10.22.172:9092/fapi/file/%s?token=%s&file_quality=original", uploadResp.Resource, fileToken)
						originalUrl := fmt.Sprintf("http://192.168.30.80:30700/fapi/file/%s?token=%s&file_quality=original", uploadResp.Resource, fileToken)

						galleryReq := &GetGalleryInfoRequest{
							ImageType: 1,
							//MemberId:  31,
							MemberId:         2,
							Prompt:           prompt,
							Url:              uploadResp.Resource,
							OriginalUrl:      originalUrl,
							Size:             size,
							ContentType:      "image/png",
							Width:            int64(imgConfig.Width),
							Height:           int64(imgConfig.Height),
							FileName:         fileName,
							ModelType:        "Midjourney",
							Version:          "v 6.0",
							MidjourneyTaskId: "1774710665532256256",
							Seed:             "4913924096",
							AdditionalType:   0,
						}
						body, _ := json.Marshal(galleryReq)
						//fmt.Println(body)
						//time.Sleep(time.Second * 10)
						sendMessage(string(body))
						fmt.Printf("upload: %v\n", uploadNum)
						uploadNum++
						//sendGrpcMsg(newUrl)
						if err != nil {
							log.Printf("failed to open PNG file %s in ZIP %s: %v", pngFileName, path, err)
							continue
						}
						defer pngFile.Close()
					}
				}
			}
		}

		return nil
	})

	if err != nil {
		log.Fatal(err)
	}
}

type UploadFileResponse struct {
	Resource string `json:"resource"`
}

// http 上传文件到AI服务器
func httpUploadFile(fileName string, file io.ReadCloser) *UploadFileResponse {

	url := "http://192.168.30.80:30700/fapi/file"
	//url := "http://10.10.22.172:9092/fapi/file"
	method := "POST"
	payload := &bytes.Buffer{}
	writer := multipart.NewWriter(payload)
	_ = writer.WriteField("file_type", "additional")
	part2,
		errFile2 := writer.CreateFormFile("file", fileName)
	_, errFile2 = io.Copy(part2, file)
	if errFile2 != nil {
		fmt.Println(errFile2)
		return nil
	}
	_ = writer.WriteField("token", fileToken)
	err := writer.Close()
	if err != nil {
		fmt.Println(err)
		return nil
	}

	client := &http.Client{}
	req, err := http.NewRequest(method, url, payload)

	if err != nil {
		fmt.Println(err)
		return nil
	}
	req.Header.Add("Content-Type", "image/png")
	req.Header.Add("Authorization", token)
	req.Header.Set("Content-Type", writer.FormDataContentType())
	res, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	//fmt.Println(string(body))

	var response = &UploadFileResponse{}
	if err := json.Unmarshal(body, response); err != nil {
		fmt.Errorf("err=%v", err)
		return nil
	}
	return response
}

// uploadFile 上传文件
func uploadFile(fileName string, size int64, reader io.Reader) (url string) {
	ctx := context.Background()
	//endpoint := "192.168.30.251:8088" // old address
	endpoint := "192.168.33.111:8088"
	accessKeyID := "cloudsrv-admin"
	secretAccessKey := "USHIRTs@20.22$pass*wd."
	useSSL := false

	// Initialize minio client object.
	minioClient, err := minio.New(endpoint, &minio.Options{
		Creds:  credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
		Secure: useSSL,
	})
	if err != nil {
		log.Fatalln(err)
	}

	// Make a new bucket called testbucket.
	bucketName := "testbucket"
	location := "us-east-1"

	err = minioClient.MakeBucket(ctx, bucketName, minio.MakeBucketOptions{Region: location})
	if err != nil {
		// Check to see if we already own this bucket (which happens if you run this twice)
		exists, errBucketExists := minioClient.BucketExists(ctx, bucketName)
		if errBucketExists == nil && exists {
			log.Printf("We already own %s\n", bucketName)
		} else {
			log.Fatalln(err)
		}
	} else {
		log.Printf("Successfully created %s\n", bucketName)
	}

	// Upload the test file
	// Change the value of filePath if the file is in another location

	// 要过滤的后缀
	//suffix := ".png"
	//// 使用 strings.TrimSuffix 过滤后缀
	//objectName := strings.TrimSuffix(fileName, suffix)
	objectName := fileName
	//contentType := "application/octet-stream"
	contentType := "image/png"

	// Upload the test file with FPutObject
	info, err := minioClient.PutObject(ctx, bucketName, objectName, reader, size, minio.PutObjectOptions{ContentType: contentType})

	if err != nil {
		log.Fatalln(err)
	}

	log.Printf("Successfully uploaded %s of size %d\n", objectName, info.Size)

	return fmt.Sprintf("http://%s/%s/%s", endpoint, bucketName, objectName)
}

func sendGrpcMsg() {
	// 连接到gRPC服务器
	//conn, err := grpc.Dial("127.0.0.1:9000", grpc.WithInsecure())
	//if err != nil {
	//	log.Fatalf("无法连接到服务器：%v", err)
	//}
	//defer conn.Close()
	//
	//// 创建gRPC客户端
	//client := v1.NewGalleryStorageInterfaceClient(conn)
	//
	////准备gRPC请求
	//req := &v1.GetUsedStorageRequest{}
	//// 创建一个新的上下文，并设置 Authorization 元数据
	//ctx := metadata.AppendToOutgoingContext(context.Background(), "authorization", "Bearer YOUR_TOKEN_HERE")
	//
	//// 发送gRPC请求
	//resp, err := client.GetUsedStorage(context.Background(), req)
	//if err != nil {
	//	log.Fatalf("调用UploadImageEmbedding失败：%v", err)
	//}
	//// 处理响应
	//log.Printf("服务器响应：%d", resp.UsedStorage)
}
